﻿using BindTryParseMVC.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Diagnostics;
using System.Threading.Tasks;

namespace BindTryParseMVC.Controllers
{
    public class ContactsController : Controller
    {
        private readonly ValidationResultErrorMessageContext _context;

        public ContactsController(ValidationResultErrorMessageContext context)
        {
            _context = context;
        }
        public async Task<IActionResult> Index()
        {
            return _context.Contact != null ?
                 View(await _context.Contact.ToListAsync()) :
                 View("Error", new ErrorViewModelContact
                 {
                     Message = "Contact is null",
                     RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier
                 });
        }

        public async Task<IActionResult> Details(Guid? id)
        {
            if (id == null || _context.Contact == null)
            {
                return NotFound();
            }

            var contact = await _context.Contact.FirstOrDefaultAsync(x => x.Id == id);
            if (contact == null)
            {
                return NotFound();
            }
            return View(contact);
        }

        public IActionResult Create()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("Id,Name,Email,PhoneNumber")] Contact contact)
        {
            if (ModelState.IsValid)
            {
                contact.Id = Guid.NewGuid();
                _context.Add(contact);
                await _context.SaveChangesAsync();
                return RedirectToAction("Index");
            }
            return View(contact);
        }

        public async Task<IActionResult> Edit(Guid? id)
        {
            if (id == null || _context.Contact == null) { return NotFound(); }
            var contact = await _context.Contact.FindAsync(id);
            if (contact == null) return NotFound();
            return View(contact);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(Guid id, [Bind("Id,Name,Email,PhoneNumber")] Contact contact)
        {
            if (id != contact.Id) return NotFound();

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(contact);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!ContactExists(contact.Id))
                        return NotFound();
                    else
                        throw;
                }
                return RedirectToAction("Index");
            }
            return View(contact);
        }

        public async Task<IActionResult> Delete(Guid? id)
        {
            if(id == null || _context.Contact == null) return NotFound();

            var contact = await _context.Contact.FirstOrDefaultAsync(x => x.Id == id);
            if (contact == null) return NotFound();
            return View(contact);
        }

        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirm(Guid id)
        {
            if (_context.Contact == null)
            {
                return View("Error", new ErrorViewModelContact
                {
                    Message = $"Contact with id {id} is null",
                    RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier
                });
            }
            var contact = await _context.Contact.FindAsync(id);
            if(contact!=null)
                _context.Contact.Remove(contact);
            else
            {
                return View("Error", new ErrorViewModelContact
                {
                    Message = $"Contact with id {id} is null",
                    RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier
                });
            }

            await _context.SaveChangesAsync();
            return RedirectToAction("Index");
        }

        private bool ContactExists(Guid id)
        {
            return (_context.Contact?.Any(e => e.Id == id)).GetValueOrDefault();
        }
    }
}
